package com.acme.bankapp.domain.email.impl;

import java.util.LinkedList;
import java.util.List;

import com.acme.bankapp.domain.email.Email;
import com.acme.bankapp.domain.email.Queue;

public class QueueImpl implements Queue {
	private final static String QUEUE_CLOSED = "Queue is already closed";
	private volatile List<Email> mails = new LinkedList<Email>();
	private volatile boolean isQueueClosed = false;
	
	public void addEmail(Email email) throws InterruptedException {
		synchronized (mails) {
			if (isQueueClosed)
				throw new IllegalStateException(QUEUE_CLOSED);
			System.out.println(Thread.currentThread().getName() + " console");
			mails.add(email);
			mails.notifyAll();
		}
	}

	public void close() {
		synchronized (mails) {
			isQueueClosed = true;
			mails.clear();
			mails.notifyAll();
		}
	}

	public Email getEmail() throws InterruptedException{
		synchronized (mails) {
			while(!isQueueClosed && mails.isEmpty()){
				mails.wait();
			}
			if (isQueueClosed){
				return null;
			}
			return mails.remove(0);
		}
	}
	
}
